import {createSlice} from "@reduxjs/toolkit";
import {getAllMaterialByPageAPI, getOneMaterialByIdAPI, getTotalMaterialAPI} from "@/apis/material.jsx";


const materialStore=createSlice({
    name:'materialInfo',
    initialState:{
        material:{},
        materialList:[],
        total:0
    },
    // 修改数据的同步方法
    reducers:{
        //     1.根据id获取一条材料信息
        getOneMaterialById(state,action){
            state.material=action.payload;
        },

        //     2.分页获取所有材料信息
        getAllMaterialByPage(state,action){
            state.materialList=action.payload;
        },
        //     3.获取所有数据条数
        getAllMaterialCount(state,action){
            state.total=action.payload;
        }
    },

})

// 解构出同步修改函数
const {getOneMaterialById,getAllMaterialByPage,getAllMaterialCount}=materialStore.actions;

// 异步请求部分
// 1.根据id获取一条材料信息
const fetchGetOneMaterialById=(id)=>{
    return async (dispatch)=>{
        const res=await getOneMaterialByIdAPI(id);
        dispatch(getOneMaterialById(res.data))
    }
}

// 2.分页获取所有材料数据
const fetchGetAllMaterialByPage=(current,sizePage)=>{
    return async (dispatch)=>{
        const res=await getAllMaterialByPageAPI(current,sizePage);
        dispatch(getAllMaterialByPage(res.data))
    }
}
// 3.获取所有数据条数
const fetchGetAllMaterialCount=()=>{
    return async (dispatch)=>{
        const res=await getTotalMaterialAPI();
        dispatch(getAllMaterialCount(res.data))
    }
}

const materialInfoReducer=materialStore.reducer;

export {getAllMaterialByPage,getOneMaterialById,fetchGetAllMaterialByPage,fetchGetOneMaterialById,fetchGetAllMaterialCount}

export default  materialInfoReducer;



